// ignore_for_file: unnecessary_statements

import 'package:flutter/material.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:ichinesereader/constants.dart';
import 'package:ichinesereader/controller/assessments.dart';
import 'package:get/get.dart';
import 'package:ichinesereader/controller/books.dart';
import 'package:ichinesereader/controller/cache.dart';
import 'package:ichinesereader/exam/dto/assessment.response.dart';
import 'package:ichinesereader/exam/util/ExamUtil.dart';
import 'package:ichinesereader/exam/widgets/BGExamWidget.dart';
import 'package:ichinesereader/models/assessment/assessmentRecordDto.dart';
import 'package:ichinesereader/models/book/BookItem.dart';
import 'package:ichinesereader/pages/common/swichEdit.dart';
import 'package:ichinesereader/pages/common/swichGraded.dart';
import 'package:ichinesereader/utils/helper.dart';
import 'package:ichinesereader/widgets/buttons/debouncedMaterialButton.dart';
import '../../models/assessment/questionRecordSection.dart';
import '../../widgets/dialogs/submitAlertDialog.dart';

class BookQuestionCollapse extends StatefulWidget {
  BookQuestionCollapse(
      {Key? key,
      required this.bookcode,
      this.questionRecordId,
      required this.recordStatus,
      required this.bookItem,
      this.readingType,
      required this.nanhaiBookKnowledgeTypes,
      required this.kind,
      this.submited,
      required this.bookQuestionCollapseSections})
      : super(key: key);
  final String bookcode;
  final String? questionRecordId;
  final String recordStatus;
  final BookItem bookItem;
  final NanhaiBookReadingTypes? readingType;
  final NanhaiBookKnowledgeTypes nanhaiBookKnowledgeTypes;
  // combine part of grammar and book quickReview model
  final List<QuestionRecordSection> bookQuestionCollapseSections;
  final String kind;
  final bool? submited;

  @override
  State<BookQuestionCollapse> createState() => _BookQuestionCollapseState();
}

class _BookQuestionCollapseState extends State<BookQuestionCollapse> {
  final AssessmentsController _assessmentsController = Get.find();
  final box = Hive.box('appconfig');
  String _lang = 'Mandarin';
  String _language = 'Simplified';
  AssessmentRecordDto dto = AssessmentRecordDto();
  //List<QuestionRecordSection> widget.bookQuestionCollapseSections = [];
  BGExamWidgetMode mode = BGExamWidgetMode.Practice;
  bool initiallyExpanded = false;
  bool isTeacherOrSchoolAdmin = false;
  List<Record> records = [];
  bool switchSave = false;
  String write = '';
  String oral = '';
  @override
  void initState() {
    // set mode for teacher and student
    if (isTeacherOrSchoolAdmin) {
      mode = BGExamWidgetMode.Review;
    } else {
      // change back to COMPLETED later because can't grade yet
      // if (widget.recordStatus == COMPLETED ) {
      if (widget.submited ?? false) {
        mode = BGExamWidgetMode.Graded;
      }
    }

    // to keep the same setting as individual book setting
    if (box.get('_text') != null) {
      _lang = box.get('_audio');
    } else {
      _lang = box.get('UserLang') ?? 'Mandarin';
    }
    if (_lang == 'No_audio') {
      _lang = 'Mandarin';
    }
    if (box.get('_audio') != null) {
      _language = box.get('_text');
    } else {
      _language = box.get('UserLanguage') ?? 'Simplified';
    }
    if (_language == 'No text') {
      _language = 'Simplified';
    }
    var username = box.get(CacheManagerKey['username'].toString());
    // data for submit grammar setting
    dto = ExamUtil.buildRecordSettingDto(null, _lang, widget.bookcode,
        widget.kind, null, null, _language, 'LIBRARY', username);
    isTeacherOrSchoolAdmin =
        box.get(CacheManagerKey['nanhairole'].toString()) ==
                Constants.NanhaiRole_Teacher ||
            box.get(CacheManagerKey['nanhairole'].toString()) ==
                Constants.NanhaiRole_SchoolAdmin;
    super.initState();
  }

  @override
  void dispose() {
    //Get.delete<AssessmentsController>();
    super.dispose();
  }

  _getAnswer(value) {}
  // switch collapse and expand for the nested grid
  void _setAll(bool isExpanded) {
    for (var i = 0; i < widget.bookQuestionCollapseSections.length; i++) {
      for (var j = 0;
          j < widget.bookQuestionCollapseSections[i].questions!.length;
          j++) {
        for (var k = 0;
            k <
                widget.bookQuestionCollapseSections[i].questions![j].question!
                    .length;
            k++) {
          widget.bookQuestionCollapseSections[i].questions![j].question![k]
              .isExpanded = isExpanded;
        }
      }
    }
    // need setState
    setState(() {});
  }

  _submitAnswers() {
    // can't not check if teacher havs graded it yet
    List<Record> records = [];
    // change to widget.bookQuestionCollapseSections
    records = ExamUtil.buildRecordList(widget.bookQuestionCollapseSections);
    dto.record = records;
    _assessmentsController
        .submitAssessmentQuestionRecord(dto, widget.bookcode)
        .then((statusMessage) {
      if (statusMessage.status == 1000) {
        showSnackMsg('Submit it successfully'.tr);
        Navigator.of(context).pop();
        Navigator.of(context).pop();
        Map<String, dynamic> mapData = statusMessage.result;
        if (widget.readingType != null && mapData['id'] != null) {
          final BooksController booksController = Get.find();
          booksController.updateBookKnowledgeItemStatus(
              widget.readingType!,
              widget.nanhaiBookKnowledgeTypes,
              widget.bookItem.bookId!,
              mapData['id']);
        }
      }
    });
  }

  _saveAnswers() {
    List<Record> records = [];
    records = ExamUtil.buildRecordList(widget.bookQuestionCollapseSections);
    dto.record = records;
    _assessmentsController
        .saveAssessmentQuestionRecord(dto, widget.bookcode)
        .then((statusMessage) {
      if (statusMessage.status == 1000) {
        Map<String, dynamic> mapData = statusMessage.result;

        if (widget.readingType != null && mapData['id'] != null) {
          final BooksController booksController = Get.find();
          booksController.updateBookKnowledgeItemStatus(
              widget.readingType!,
              widget.nanhaiBookKnowledgeTypes,
              widget.bookItem.bookId!,
              mapData['id']);
        }
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      scrollDirection: Axis.vertical,
      primary: false,
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Center(
          child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.end,
              children: [
                Container(
                  width: (MediaQuery.of(context).size.width) * 0.8,
                  child:
                      Row(mainAxisAlignment: MainAxisAlignment.end, children: [
                    SizedBox(height: 25),
                    MaterialButton(
                        color: Theme.of(context).colorScheme.secondary,
                        onPressed: () {
                          _setAll(true);
                        },
                        child: Text('Expanded All'.tr,
                            style: TextStyle(color: Colors.white))),
                    SizedBox(width: 25),
                    MaterialButton(
                        color: Theme.of(context).colorScheme.secondary,
                        onPressed: () {
                          _setAll(false);
                        },
                        child: Text('Collapsed All'.tr,
                            style: TextStyle(color: Colors.white))),
                  ]),
                ),
                SizedBox(height: 5),
                Column(
                  children: [
                    // add two elements in each loop iteration we had to put the two into a list and unwrap it with the ... spread operator
                    for (var i = 0;
                        i < widget.bookQuestionCollapseSections.length;
                        i++) ...[
                      Column(children: [
                        for (var j = 0;
                            j <
                                widget.bookQuestionCollapseSections[i]
                                    .questions!.length;
                            j++)
                          ExpansionPanelList(
                            expansionCallback: (int index, bool isExpanded) {
                              setState(() {
                                widget
                                    .bookQuestionCollapseSections[i]
                                    .questions![j]
                                    .question![index]
                                    .isExpanded = !isExpanded;
                              });
                            },
                            children: widget.bookQuestionCollapseSections[i]
                                .questions![j].question!
                                .map<ExpansionPanel>((QuestionItem item) {
                              return ExpansionPanel(
                                headerBuilder:
                                    (BuildContext context, bool isExpanded) {
                                  return ListTile(
                                    tileColor: item.answer!.length > 0
                                        ? Color.fromARGB(255, 186, 223, 232)
                                        : Color.fromARGB(255, 233, 236, 237),
                                    title: Column(
                                      mainAxisAlignment:
                                          MainAxisAlignment.start,
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      children: [
                                        // // for grammar
                                        // if (widget
                                        //         .bookQuestionCollapseSections[i]
                                        //         .category !=
                                        //     null)
                                        //   Text(
                                        //       '${widget.bookQuestionCollapseSections[i].category}/ ${widget.bookQuestionCollapseSections[i].subCategory}',
                                        //       style: TextStyle(
                                        //           color: Colors.black)),
                                        // // for quick Review
                                        // if (widget
                                        //         .bookQuestionCollapseSections[i]
                                        //         .partType !=
                                        //     null)
                                        //   Text(
                                        //       '${widget.bookQuestionCollapseSections[i].partType}',
                                        //       style: TextStyle(
                                        //           color: Colors.black)),
                                      ],
                                    ),
                                  );
                                },
                                body: GestureDetector(
                                  child: Container(
                                    padding:
                                        const EdgeInsets.fromLTRB(15, 0, 15, 0),
                                    child: Column(
                                      mainAxisAlignment:
                                          MainAxisAlignment.start,
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      children: [
                                        // the following code causes large space
                                        ExamUtil.buildHeadInfoWidget(
                                            widget
                                                .bookQuestionCollapseSections[i]
                                                .questions![j]
                                                .content,
                                            context),
                                        // 一旦 save 后就会变成锁定状态，按钮变成 Edit
                                        if (widget.bookQuestionCollapseSections[i]
                                                    .partType ==
                                                "WRITING" &&
                                            item.answer!.length > 0)
                                          SwitchEdit(
                                            questionItem: item,
                                            partType: "WRITING",
                                            questionId: widget
                                                .bookQuestionCollapseSections[i]
                                                .questions![j]
                                                .id!,
                                            nanhaiBookKnowledgeTypes:
                                                widget.nanhaiBookKnowledgeTypes,
                                            getAnswer: _getAnswer,
                                            mode: mode,
                                            isTeacherOrSchoolAdmin:
                                                isTeacherOrSchoolAdmin,
                                            // it undone even after submited
                                            //recordStatus: widget.recordStatus,
                                            recordStatus:
                                                widget.submited ?? false
                                                    ? "COMPLETED"
                                                    : "UNDONE",
                                            saveAnswers: _saveAnswers,
                                          ),
                                        if (widget.bookQuestionCollapseSections[i]
                                                    .partType ==
                                                "WRITING" &&
                                            item.answer!.length > 0)
                                          SizedBox(height: 15),
// quick response only for options --to do later when there is data
                                        if (!(widget
                                                    .bookQuestionCollapseSections[
                                                        i]
                                                    .partType ==
                                                "WRITING" &&
                                            item.answer!.length > 0)) ...[
                                          SwitchGraded(
                                            questionItem: item,
                                            partType: widget
                                                    .bookQuestionCollapseSections[
                                                        i]
                                                    .partType ??
                                                '',
                                            questionId: widget
                                                .bookQuestionCollapseSections[i]
                                                .questions![j]
                                                .id!,
                                            nanhaiBookKnowledgeTypes:
                                                widget.nanhaiBookKnowledgeTypes,
                                            getAnswer: _getAnswer,
                                            mode: mode,
                                            isTeacherOrSchoolAdmin:
                                                isTeacherOrSchoolAdmin,
                                            recordStatus:
                                                widget.submited ?? false
                                                    ? "COMPLETED"
                                                    : "UNDONE",
                                            saveAnswers: _saveAnswers,
                                          ),
                                          // BGExamWidget(
                                          //     questionItem: item,
                                          //     getAnswer: _getAnswer,
                                          //     // questionId: item.questions![0].id,
                                          //     mode: mode),
                                          SizedBox(height: 15),
                                          // Row(
                                          //   mainAxisAlignment:
                                          //       MainAxisAlignment.end,
                                          //   children: [
                                          //     //SizedBox(height: 35),
                                          //     Visibility(
                                          //       visible:
                                          //           isTeacherOrSchoolAdmin ==
                                          //                   false &&
                                          //               widget.recordStatus !=
                                          //                   'COMPLETED',
                                          //       child: DebouncedMaterialButton(
                                          //           debounceTimeMs: 800,
                                          //           color: Theme.of(context)
                                          //               .colorScheme
                                          //               .secondary,
                                          //           onPressed: () {
                                          //             _saveAnswers();
                                          //           },
                                          //           child: Text('Save'.tr,
                                          //               style: TextStyle(
                                          //                   color:
                                          //                       Colors.white))),
                                          //     ),
                                          //   ],
                                          // )
                                        ]
                                      ],
                                    ),
                                  ),
                                ),
                                isExpanded: item.isExpanded,
                              );
                            }).toList(),
                          ),
                      ]),
                    ],
                  ],
                ),
                SizedBox(height: 15),
                Container(
                  width: (MediaQuery.of(context).size.width) * 0.8,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      //SizedBox(height: 35),
                      Visibility(
                        visible: isTeacherOrSchoolAdmin == false &&
                            !widget.submited!,
                        child: DebouncedMaterialButton(
                            debounceTimeMs: 800,
                            color: Theme.of(context).colorScheme.secondary,
                            onPressed: () {
                              // add reminder
                              //_submitAnswers();
                              showGeneralDialog(
                                  context: context,
                                  transitionDuration:
                                      Duration(milliseconds: 400),
                                  pageBuilder: (bc, ania, anis) {
                                    return SubmitAlertDialog(
                                        reminder:
                                            'Are you sure you want to submit?'
                                                .tr,
                                        message:
                                            'After submit, it will send to teacher for grading. You could still edit it before gradding. Once graded by teacher, you can not edit it again.'
                                                .tr,
                                        submitAnswers: _submitAnswers);
                                  });
                            },
                            child: Text('Submit'.tr,
                                style: TextStyle(color: Colors.white))),
                      ),
                    ],
                  ),
                ),
              ]),
        ),
      ),
    );
  }
}
